<template>
  <ElDialog
    v-model="dialogVisible"
    title="完善个人信息"
    width="700"
    destroy-on-close
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
  >
    <div v-loading="loading">
      <form-create
        v-if="formRule.length > 0"
        v-model="formData"
        v-model:api="fApi"
        :rule="formRule"
        :option="formOption"
        :key="formKey"
      />
      <div v-else class="text-center text-gray-500 py-40px"> 暂无需要填写的信息 </div>
    </div>
    <!-- <template #footer>
      <el-button
        type="primary"
        @click="handleSubmit"
        :loading="submitting"
        :disabled="formRule.length === 0"
      >
        提交
      </el-button>
    </template> -->
  </ElDialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import * as UserApi from '@/api/system/user'
import { useUserStore } from '@/store/modules/user'

defineOptions({ name: 'UserProfileDialog' })

const props = defineProps<{
  modelValue: boolean
}>()

const emit = defineEmits(['update:modelValue', 'success'])

const message = useMessage()
const userStore = useUserStore()

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const designer = ref()
const loading = ref(false)
const submitting = ref(false)
const formData = ref({})
const fApi = ref()
const formRule = ref([])
const formOption = ref({
})
const formKey = ref(0) // 用于强制重新渲染

// 获取表单配置
const loadFormConfig = async () => {
  loading.value = true
  try {
    const data = await UserApi.getUserProfileConfig()
    console.log('获取到的配置数据:', data)
    if (data) {
      // 设置表单设计器的数据
      const { rule, options } = JSON.parse(data)

      // rule 和 option 本身也是 JSON 字符串，需要再次解析
      if (rule) {
        if (typeof rule === 'string') {
          formRule.value = JSON.parse(rule)
        } else {
          formRule.value = rule
        }
      } else {
        formRule.value = []
      }

      // 合并配置，确保保留 submitBtn 和 resetBtn 设置
      if (options) {
        let optionObj = options
        if (typeof options === 'string') {
          optionObj = JSON.parse(options)
        }
        formOption.value = {
          ...optionObj,
          onSubmit: (formData: any) => {
            handleSubmit(formData)
          }
        }
      }
      formKey.value = formKey.value++
    } else {
      console.warn('未获取到配置数据')
      formRule.value = []
    }
  } catch (error) {
    console.error('获取表单配置失败:', error)
    message.error('获取表单配置失败')
    formRule.value = []
  } finally {
    loading.value = false
  }
}

// 提交表单
const handleSubmit = async (formDataFromFormCreate?: any) => {
  try {
    submitting.value = true
    const userId = userStore.user?.id
    // tenantId 从 user store 中获取，如果没有则使用默认值
    const tenantId = (userStore.user as any)?.tenantId || 1

    // 使用传入的表单数据，如果没有则使用 formData.value
    const dataToSubmit = formDataFromFormCreate || formData.value

    // 将表单数据转换为 JSON 字符串
    const fieldValue = JSON.stringify(dataToSubmit)

    await UserApi.saveUserProfile({
      userId,
      tenantId,
      fieldValue
    })

    message.success('提交成功')
    dialogVisible.value = false
    emit('success')
  } catch (error: any) {
    console.error('提交失败:', error)
    message.error('提交失败')
  } finally {
    submitting.value = false
  }
}

// 监听对话框打开，加载表单配置
watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      loadFormConfig()
    }
  },
  { immediate: true }
)
</script>

<style scoped>
:deep(.el-dialog__body) {
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
}
</style>
